package dao;

import bean.UserBean;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImp extends BaseDao implements IUserDao{
    @Override
    public UserBean findByGrad(String name, String pwd) {
        UserBean user= null;
        this.setConnection();

        try {
            ps = con.prepareStatement("select * from t_user where u_userName=? and u_password=?");
            ps.setObject(1,name);
            ps.setObject(2,pwd);

            rs=ps.executeQuery();

            if(rs.next()){
                user = this.getUser();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
        return user;
    }

    @Override
    public void add(UserBean userBean) {
        this.setConnection();

        try {
            ps = con.prepareStatement("insert into t_user (u_userName,u_password,u_birthday,u_money,u_phone) " +
                    "values(?,?,?,?,?) ");

            ps.setObject(1, userBean.getUserName());
            ps.setObject(2, userBean.getPassword());
            ps.setObject(3,userBean.getBirthday());
            ps.setObject(4,userBean.getMoney());
            ps.setObject(5,userBean.getPhone());


            ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }
    @Override
    public List<UserBean> findAll() {

        List<UserBean> list=new ArrayList<>();
        this.setConnection();
        try {
            ps=con.prepareStatement("select * from t_user");
            rs= ps.executeQuery();
            while (rs.next()){
                list.add(this.getUser());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
        return list;
    }
    public UserBean getUser() throws SQLException {
        UserBean userObj = new UserBean();
        userObj.setID(rs.getInt("pk_userId"));
        userObj.setUserName(rs.getString("u_userName"));
        userObj.setPassword(rs.getString("u_password"));
        userObj.setBirthday(LocalDate.parse(rs.getString("u_birthday")));
        userObj.setMoney(rs.getInt("u_money"));
        userObj.setPhone(rs.getString("u_phone"));
        return userObj;
    }
}
